package com.xujl.fastlib.http

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.xujl.fastlib.utils.StringUtils
import okhttp3.ResponseBody
import retrofit2.Converter
import java.io.IOException


class MyGsonResponseBodyConverter<T>(
        private val gson: Gson,
        private val adapter: TypeAdapter<T>
) : Converter<ResponseBody, T> {

    @Throws(IOException::class)
    override fun convert(value: ResponseBody): T? {
        val json = value.string()
        val response2 = gson.fromJson<BaseResponse2>(json, BaseResponse2::class.java)
        if (!StringUtils.equals(response2.code, ApiDisposableObserver.CodeRule.CODE_200)) {
            value.close()
            throw CommitException(response2.code, response2.description)
        }
        try {
            val result = adapter.fromJson(json)
            return result
        } catch (e: Exception) {
            throw JsonParseException().setJson(json)
        } finally {
            value.close()
        }


//        //正常解析
//        val mediaType = value.contentType()
//        val charset = if (mediaType != null) mediaType.charset(UTF_8) else UTF_8
//        val bis = ByteArrayInputStream(response.toByteArray())
//        val reader = InputStreamReader(bis, charset)
//        val jsonReader = gson.newJsonReader(reader)
//        try {
//            return adapter.read(jsonReader)
//        } finally {
//            value.close()
//        }
    }
}
